<?php

class Template
{
    private $menu;
    private $recordId;
    private $page;
    private $nameId;
    private $pattern;
    private $_db;
    private $shorts;
    private $view_type;
    private $menu_info = array();

    public function __construct($menu, $recordId,$nameId = NULL, $page = NULL) 
    {
        $this->menu = $menu;
        $this->recordId = $recordId;
        $this->page = $page;
        $this->nameId = $nameId;
        $this->_db = Db::getInstance();
    }
    
    public function viewTemplate()
    {
        $this->createPattern();
        //echo $this->menu.'   '.$this->recordId.'   '.$this->page.'   '.$this->nameId;
        //echo $this->pattern;
        $this->convertPattern();
        //echo $this->view_type;
        //var_dump($this->shorts);
        echo $this->pattern;
        //$this->shortsToArray();
        //var_dump($this->shorts);
    }
    
    private function createPattern()
    {
        $table = $this->menu."_menu";
        $r = $this->_db->q("select * from ".$table." where id = ".$this->recordId);
        $res = mysql_fetch_assoc($r);
        $design_view = $res['design'];
        $view = $res['view'];
        $this->menu_info = $res;
        
        $fileName = $_SERVER['DOCUMENT_ROOT']."/themes/".$design_view;
       
        if (!@file_exists($fileName))
        {
            die ("Design не найден");
        }
        
        ob_start();
        include $fileName;
        $design_text = ob_get_clean();
        
        if (preg_match('/^short[A-Za-z0-9_.]*$/', $res['view']))
        {
            $this->view_type = 'short';
        }
        
        if (preg_match('/^long[A-Za-z0-9_.]*$/', $res['view']))
        {
            $this->view_type = 'long';
        }
        
        if ($this->nameId != NULL && preg_match('/^short[A-Za-z0-9_.]*$/', $res['view']) )
        {
            $view = 'long.tpl';
            $this->view_type = 'long';
        }
        
        $fileName = $_SERVER['DOCUMENT_ROOT']."/themes/tables/".$res['table']."/".$view;
        if (!@file_exists($fileName))
        {
            die ("View не найден");
        }
        
        ob_start();
        include $fileName;
        $view_text = ob_get_clean();
        
        $tmp_pattern = str_ireplace('[CONTENT]', $view_text, $design_text);
        
        preg_match_all('/\[include\s"([a-z0-9]+)"\s"([a-z0-9.]+)"\]/xi', $tmp_pattern, $incs, PREG_SET_ORDER);

        foreach ($incs as $inc)
        {
            $fName = $_SERVER['DOCUMENT_ROOT']."/themes/tables/".$inc[1]."/".$inc[2];
            
            if (!@file_exists($fName))
            {
                $tmp_pattern = str_replace ($inc[0], '', $tmp_pattern);
                continue;
            }
            
            ob_start();
            include $fName;
            $str = ob_get_clean();
            $tmp_pattern = str_replace ($inc[0], $str, $tmp_pattern);
        }
        
        $this->pattern = $tmp_pattern;
        $this->shorts = $this->shortsToArray();
        
    }
    
    private function shortsToArray($pattern = NULL)
    {
        if ($pattern == NULL)
        {
            $pattern = &$this->pattern;
        }
        preg_match_all('/(\[[\/a-z0-9.=\s*"|_;\'`-]+\])/xi', $pattern, $tmp_shorts, PREG_OFFSET_CAPTURE);

        $addr1 = null;
        $addr2 = null;
        
        //var_dump($tmp_shorts);

        foreach($tmp_shorts[0] as $short)
        {
            $start_body = null;
            if (preg_match('/^\[start .*\]/xi', $short[0]))
            {
                $addr1 = $short[1];
            }
  
            if (preg_match('/^\[\/start]/xi', $short[0]) && $addr1 != NULL)
            {
                $addr2 = $short[1] + strlen($short[0]);
                $length = $addr2 - $addr1;
                $start_body = substr($pattern, $addr1, $length);
                $addr1 = null;
                $addr2 = null;
    //var_dump($start_body);
            }

            if ($addr1 == null && $addr2 == null && $start_body == null)
            {
                $shorts[] = $short[0];
            }
            elseif ($start_body != null)
            {
                $shorts[] = $start_body;
            }
  //var_dump($c);
        }
        return $shorts;
    }

    private function convertPattern ()
    {
        for ($i=0; $i<count($this->shorts); $i++)
        {
            preg_match('/\[([a-z0-9-]+)/xi', $this->shorts[$i], $short_tmp);
            //var_dump($short_tmp);
            $short_name = strtolower($short_tmp[1]);
            $method = $short_name."_short";
            
            //var_dump($method);
            
            $repl = $this->$method($this->shorts[$i]);            
            $this->pattern = str_ireplace($this->shorts[$i], $repl, $this->pattern);    
         }
        
    }
    
    private function getParam($short_str)
    {
        if (!preg_match_all('/([a-z0-9_-]+=\"[a-z0-9_`\*\s;-]+\")/xi', $short_str, $arr))
        {
            return false;
        }
        $params = array();
        foreach ($arr[0] as $val)
        {
            preg_match ('/([a-z0-9]+)=\"([a-z0-9;_`\*\s-]+)\"/xi', $val, $k);
            $params[$k[1]] = $k[2];
        }
        return $params;
    }

    private function title_short($short_str)
    {
        if (preg_match('/\[title\=\"([a-z0-9_-]+)\"\]/xi', $short_str, $title_tmp))
        {
            //var_dump($title_tmp);
            if ($this->nameId != null)
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `nameId` = '".$this->nameId."'");
                //var_dump($t);
                if ($t == NULL)
                {
                    return '';
                }
                //var_dump($t[$title_tmp[1]]);
                $this->pattern = str_ireplace('[title]', $t[$title_tmp[1]], $this->pattern);
                return '';
            }
            else
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `id` = '".$this->menu_info['record']."'");
                if ($t == NULL)
                {
                    return '';
                }
                $this->pattern = str_ireplace('[title]', $t[$title_tmp[1]], $this->pattern);
                return '';
            }
        }
        elseif ($this->menu_info['title'] == NULL || ($this->nameId != null && preg_match('/^short[A-Za-z0-9_.]*$/', $this->menu_info['view'])))
        {
            return '[title]';
        }
        else
        {
            return $this->menu_info['title'];
        }
    }
    
    private function keywords_short ($short_str)
    {
        if (preg_match('/\[keywords\=\"([a-z0-9_-]+)\"\]/xi', $short_str, $keywords_tmp))
        {
            //var_dump($title_tmp);
            if ($this->nameId != null)
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `nameId` = '".$this->nameId."'");
                //var_dump($t);
                if ($t == NULL)
                {
                    return '';
                }
                //var_dump($t[$title_tmp[1]]);
                $this->pattern = str_ireplace('[keywords]', $t[$keywords_tmp[1]], $this->pattern);
                return '';
            }
            else
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `id` = '".$this->menu_info['record']."'");
                if ($t == NULL)
                {
                    return '';
                }
                $this->pattern = str_ireplace('[keywords]', $t[$keywords_tmp[1]], $this->pattern);
                return '';
            }
        }
        elseif ($this->menu_info['keyword'] == NULL || ($this->nameId != null && preg_match('/^short[A-Za-z0-9_.]*$/', $this->menu_info['view'])))
        {
            return '[keywords]';
        }
        else
        {
            return $this->menu_info['keyword'];
        }
    }
    
    private function description_short ($short_str)
    {
        if (preg_match('/\[description\=\"([a-z0-9_-]+)\"\]/xi', $short_str, $description_tmp))
        {
            //var_dump($title_tmp);
            if ($this->nameId != null)
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `nameId` = '".$this->nameId."'");
                //var_dump($t);
                if ($t == NULL)
                {
                    return '';
                }
                //var_dump($t[$title_tmp[1]]);
                $this->pattern = str_ireplace('[description]', $t[$description_tmp[1]], $this->pattern);
                return '';
            }
            else
            {
                $t = $this->_db->qr("select * from `".$this->menu_info['table']."` where `id` = '".$this->menu_info['record']."'");
                if ($t == NULL)
                {
                    return '';
                }
                $this->pattern = str_ireplace('[description]', $t[$description_tmp[1]], $this->pattern);
                return '';
            }
        }
        elseif ($this->menu_info['description'] == NULL || ($this->nameId != null && preg_match('/^short[A-Za-z0-9_.]*$/', $this->menu_info['view'])))
        {
            return '[description]';
        }
        else
        {
            return $this->menu_info['description'];
        }
    }
    
    private function css_short ($short_str)
    {
        $css = new UserCache();
        return $css->addCss();
    }
    
    private function js_short ($short_str)
    {
        $js = new UserCache();
        return $js->addJS();
    }


    private function start_short ($short_str)
    {
        //var_dump($short_str);
        $shorts = $this->shortsToArray($short_str);
        $params = $this->getParam($shorts[0]);
        
        //var_dump($params);
        
        if (!$params)
        {
            return '';
        }
        
        $short_str = preg_replace('/\[\/?start [^\]]*\]/xi', '', $short_str);
        array_shift($shorts);
        array_pop($shorts);
        $tmp_str = '';
        if (isset ($params['sql']))
        {
            $data = $this->_db->qr($params['sql']);
        }
        elseif (isset ($params['view']) && isset($params['table'])) 
        {
            $tmp_sql = $this->_db->qr("select * from `".$params['table']."_views` where nameId = '".$params['view']."'");
            $sql = $tmp_sql['sql'];
            $data = $this->_db->qr($sql);
        }
        else
        {
            return '';
        }
       
        $cnt = count($data);
        
        if ($cnt == 0)
        {
            return 'Нет данных';
        }
        
        for ($i = 0; $i<$cnt; $i++)
        {
            $tmp_str = $tmp_str.$short_str;
        }
        
        //var_dump($shorts);
        
        
        foreach ($shorts as $short)
        {
            for ($i = 0; $i<$cnt; $i++)
            {
                preg_match('/\[([a-z0-9-]+)/xi', $short, $short_tmp);
                $short_name = strtolower($short_tmp[1]);
                $method = $short_name."_short";
                $repl = $this->$method($short, $data[$i]);
                $pat = preg_quote($short);
                $tmp_str = preg_replace('/'.$pat.'/', $repl, $tmp_str, 1);
            }
        }
        
        //var_dump($short_str);
        return $tmp_str;
    }
    
    private function value_short ($short_str, $data)
    {
        preg_match ('/\[value\=\"([a-z0-9_-]+)\"\]/xi', $short_str, $key);
        return $data[$key[1]];
    }
    
    private function sitename_short ($short_str)
    {
        $sn = $this->_db->qr("select * from `options` where `key` = 'sitename'");
        return $sn['value'];
    }
    
    public function __call($name, $arguments) 
    {
        return 'tag_'.$name;
    }
    
}